const app = getApp();
Page({

  data: {
    currentIndex: 1,
    pageSize: 10,
    messages: []
  },

  onLoad: function(){
    getMessages(this);
  },

  onReady: function () {
    
  },

  onShow: function(){
    this.onLoad();
  },

  
  //下拉到底触发刷新函数
  onReachBottom:function(){
    this.setData({
      pageSize: this.data.pageSize + 10
    });
    getMessages(this);
  },

  //下拉刷新
  onPullDownRefresh: function(){
    this.setData({
      currentIndex: 1
    });
    getMessages(this);
  },


  //转跳到添加页面函数
  add: function(){
    wx.navigateTo({
      url: '../addSocialContact/addSocialContact',
    })
  },

  goToDetail: function(e){
    console.log(e);
    wx.navigateTo({
      url: '../socialContactDetail/socialContactDetail?messageId=' + e.currentTarget.dataset.id,
    })
  }
  
})



const getMessages = function (_this) {
  wx.request({
    url: 'https://dorm.dormassistant.wang:8080/message/getAllMessageTitles',
    method: "GET",
    data: {
      currIndex: _this.data.currentIndex,
      pageSize: _this.data.pageSize
    },
    success: function (res) {
      var tempMessages = res.data.messages;
      console.log(res.data.messages)
      if(tempMessages.length === 0) {
        wx.showToast({
          title: "没有最新的消息",
          icon: '',
          duration: 2500
        });
        
        return;
      }
      for(var i=0; i<tempMessages.length; i+=1){
        tempMessages[i].time = tempMessages[i].time.split("T")[0];
      }
      _this.setData({
        messages:  tempMessages
      });
    },
    fail: function (res) {
      wx.showToast({
        title: "网络故障",
        icon: '',
        duration: 2000
      });
    }
  });
}
